import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../helper/AppUtil.dart';
import '../../helper/ability.dart';
import '../../helper/constant.dart';
import '../../repo/api_server.dart';
import '../../repo/settings_repo.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key, required this.settingRepo});

  final SettingRepository settingRepo;

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  @override
  void initState() {
    // preloadImages();
    super.initState();
    initSetup();
  }
  
  void initSetup() async {
    final capabilities = await APIServer().capabilities(cache: false);
    Ability().init(widget.settingRepo, capabilities);

    var value = await AppUtil().isFirstTime();
    if (value) {
      // 首次设置2次
      SharedPreferences prefs = await SharedPreferences.getInstance();
      await prefs.setInt(FREE_COUNT_KEY, 2);

      FlutterNativeSplash.remove();
      //首次加载引导页
      context.pushReplacement('/guide');
      return;
    }

    var isLogin = await AppUtil().isLogin();
    FlutterNativeSplash.remove();
    if (isLogin) {
      final user = await APIServer().getUserInfo();
      AppUtil().touristLoginModel = user;

      if ((user.isVip ?? 0) == 1) {
        context.go(Ability().homeRoute);
      } else {
        context.pushReplacement('/payment');
      }
    } else {
      context.pushReplacement('/login');
    }
  }

  // 在组件构建之前预加载图片
  Future<void> preloadImages() async {
    final images = [
      'images/Chat3.5.png',
      'images/Chat5.0.png',
    ];
    for (var image in images) {
      await precacheImage(AssetImage(image), context);
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
